package com.application.meizhi.ui.fragment.douban;

import android.content.Intent;
import android.os.Bundle;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;


import com.application.meizhi.R;
import com.application.meizhi.adapter.DouBanListAdapter;
import com.application.meizhi.base.MeiziConfig;

import com.application.meizhi.model.douban.DouBanMeiZhi;
import com.application.meizhi.persenter.douban.DouBanSinglePresenter;
import com.application.meizhi.ui.activity.douban.DouBanDetailActivity;
import com.application.meizhi.ui.fragment.DelayFragment;
import com.application.meizhi.ui.iView.douban.IDouBanSingleView;

import com.application.meizhi.ui.widget.LoadingFooter;

import com.application.meizhi.uitl.DialogUtils;
import com.application.meizhi.uitl.RecyclerViewStateUtils;
import com.orhanobut.logger.Logger;
import com.zeng.headandfooterlibrary.EndlessRecyclerOnScrollListener;

import com.zeng.headandfooterlibrary.HeaderAndFooterRecyclerViewAdapter;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;

/**
 * Created by gskl on 16/10/12.
 */

public class DouBanSingleFragment extends DelayFragment<DouBanSinglePresenter> implements IDouBanSingleView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    @BindView(R.id.ptrFrame)
    PtrFrameLayout mFrameLayout;

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private Integer page = 1;

    private DouBanListAdapter mAdapter;


    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;

    private int mCurrentCount = 0;//当前数据

    public static DouBanSingleFragment newInstance(String param1, String param2) {
        DouBanSingleFragment fragment = new DouBanSingleFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void initView() {
        initRefreshLayout();

        initRecycler();
        /*完成初始化*/
        isPrepared = true;
        /*
        * 因为setUserVisibleHint会比onCreateView先执行，为了防止空指针错误，需要执行了咋样load();
        * */
        lazyLoad();
    }

    @Override
    public void lazyLoad() {
        /*
        * 判断是否满足条件
        * */
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }

        DialogUtils.showDialog(getActivity());
        presenter.getDouBan(mParam2, page);
        mHasLoadedOnce = true;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_list;
    }

    @Override
    protected void initPresenter() {
        presenter = new DouBanSinglePresenter(getActivity(), this);
        presenter.init();
    }

    private void initRecycler() {


        mAdapter = new DouBanListAdapter(getActivity());

        HeaderAndFooterRecyclerViewAdapter adapter = new HeaderAndFooterRecyclerViewAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(mScrollListener);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setHasFixedSize(true);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);

        mAdapter.setOnItemClickListener(position -> {

            Intent intent = new Intent(getActivity(), DouBanDetailActivity.class);
            intent.putExtra(DouBanDetailActivity.ARG_PARAM1, (ArrayList) mAdapter.getDataSet());
            intent.putExtra(DouBanDetailActivity.ARG_PARAM2, position);
            startActivity(intent);

        });
    }

    private void initRefreshLayout() {

        MaterialHeader header = new MaterialHeader(getActivity());
        header.setPadding(0, PtrLocalDisplay.dp2px(20), 0, PtrLocalDisplay.dp2px(20));
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        mFrameLayout.setDurationToCloseHeader(1000);
        mFrameLayout.setHeaderView(header);
        mFrameLayout.addPtrUIHandler(header);
        mFrameLayout.setPinContent(true);//设置为true时content的内容位置将不会改变

        mFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                presenter.getDouBan(mParam2, page);
            }
        });

    }

    private void refreshComplete() {
        if (mFrameLayout.isRefreshing()) {
            mFrameLayout.refreshComplete();
        }
    }

    @Override
    public void showDouBanList(List<DouBanMeiZhi> lists) {
        DialogUtils.hintDialog();
        refreshComplete();

        mCurrentCount = lists.size();

        if (page == 1) {
            mAdapter.resetDataSet(lists);
        } else {
            mAdapter.addDataSetToEnd(lists);

        }
        page++;
        RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
    }

    @Override
    public void error(String s) {
        DialogUtils.hintDialog();
        refreshComplete();
        RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, MeiziConfig.PAGE_SIZE, LoadingFooter.State.NetWorkError, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.getDouBan(mParam2, page);
            }
        });

    }

    @Override
    public void noList() {
        DialogUtils.hintDialog();
        refreshComplete();
        Logger.d("noList");
    }

    private EndlessRecyclerOnScrollListener mScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                Logger.d("the state is Loading, just wait..");
                return;
            }
            if (mCurrentCount < MeiziConfig.PAGE_SIZE) {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, MeiziConfig.PAGE_SIZE, LoadingFooter.State.TheEnd, null);
            } else {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, MeiziConfig.PAGE_SIZE, LoadingFooter.State.Loading, null);
                presenter.getDouBan(mParam2, page);
            }
        }
    };
}
